import { Component, OnInit } from '@angular/core'
import { FormBuilder, Validators, FormGroup } from '@angular/forms'
import { NzMessageService } from 'ng-zorro-antd'

import { StoreNewBaseClass } from '../baseClass'
import { ChargeStoreService } from '../charge-base.service'
import { makeAllControlDirty } from 'app/utils/helpers'
import { durationReg } from 'app/utils/contraints'
import { StoreInfo } from '@shared/interfaces/trade'
import { ValidateOrderAmount } from './order-amount.validator'
import { I18NService } from '@core'

@Component({
  selector: 'app-trade-charge-new-order',
  templateUrl: './order.component.html',
  styles: [],
})
export class TradeChargeNewOrderComponent implements OnInit {
  validateForm: FormGroup

  isLoaded = false

  // 交易金额的精度(decimal)
  amountPrecision = 2

  constructor(
    public msg: NzMessageService,
    public fb: FormBuilder,
    public storeService: ChargeStoreService,
    private i18n: I18NService,
  ) {
    this.validateForm = this.fb.group({})
  }

  ngOnInit() {
    const systemInfo = this.storeService.value.systemInfo
    this.storeService.getStoreInfo(systemInfo.intStoreCode).subscribe((storeInfo: StoreInfo) => {
      this.isLoaded = true
      const currency = storeInfo.currencies[0]
      this.storeService.value.orderInfo.currency = currency
      this.amountPrecision = currency.decimal
      this.initValidateForm()
    })
  }

  initValidateForm() {
    const orderInfo = this.storeService.value.orderInfo
    this.validateForm = this.fb.group({
      currency: [{ value: orderInfo.currency.code, disabled: true }],
      amount: [orderInfo.amount, [Validators.required, ValidateOrderAmount]],
      duration: [orderInfo.duration, [Validators.required, Validators.pattern(durationReg)]],
      commodity: [orderInfo.commodity, [Validators.required, Validators.maxLength(128)]],
      description: [orderInfo.description, [Validators.required, Validators.maxLength(128)]],
    })
  }

  checkValid(): boolean {
    if (this.validateForm.valid) {
      this.pushDataToStore()
      return true
    }

    makeAllControlDirty(this.validateForm)
    this.msg.error(this.trans('GENERAL.NOTIFICATION.VALIDATION_FAIL'))
    return false
  }

  pushDataToStore(): void {
    const store = this.storeService.value
    const formValue = this.validateForm.value
    store.orderInfo.amount = formValue.amount
    store.orderInfo.duration = formValue.duration
    store.orderInfo.commodity = formValue.commodity
    store.orderInfo.description = formValue.description
  }

  trans(key: string, params?: Object): string {
    return this.i18n.fanyi(key, params)
  }
}
